<template>
  <div class="batch-tracking-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="batch-card">
          <template #header>
            <div class="card-header">
              <h3>批次/效期追踪</h3>
              <el-button type="primary" @click="createBatch">新建批次</el-button>
            </div>
          </template>
          
          <!-- 搜索和过滤区域 -->
          <div class="filter-container">
            <el-form :inline="true" :model="filterForm" class="filter-form">
              <el-form-item label="物料编码">
                <el-input v-model="filterForm.materialCode" placeholder="请输入物料编码" clearable />
              </el-form-item>
              <el-form-item label="批次号">
                <el-input v-model="filterForm.batchNumber" placeholder="请输入批次号" clearable />
              </el-form-item>
              <el-form-item label="仓库">
                <el-select v-model="filterForm.warehouseId" placeholder="请选择仓库" clearable>
                  <el-option 
                    v-for="warehouse in warehouses" 
                    :key="warehouse.id" 
                    :label="warehouse.name" 
                    :value="warehouse.id" 
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
                  <el-option label="在库" value="in_stock" />
                  <el-option label="已出库" value="out_of_stock" />
                  <el-option label="已过期" value="expired" />
                  <el-option label="即将过期" value="expiring_soon" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="searchBatches">搜索</el-button>
                <el-button @click="resetFilter">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
          
          <!-- 批次列表 -->
          <el-table
            :data="batchList"
            border
            style="width: 100%"
            v-loading="loading"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="batchNumber" label="批次号" width="120" sortable />
            <el-table-column prop="materialCode" label="物料编码" width="120" />
            <el-table-column prop="materialName" label="物料名称" width="180" />
            <el-table-column prop="quantity" label="数量" width="100" sortable />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="manufacturingDate" label="生产日期" width="120" sortable />
            <el-table-column prop="expiryDate" label="过期日期" width="120" sortable />
            <el-table-column prop="remainingDays" label="剩余有效期" width="120" sortable>
              <template #default="scope">
                <el-tag :type="getExpiryTagType(scope.row.remainingDays)">
                  {{ scope.row.remainingDays }} 天
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="warehouseName" label="仓库" width="120" />
            <el-table-column prop="locationCode" label="货位" width="120" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusTagType(scope.row.status)">
                  {{ getStatusLabel(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="160">
              <template #default="scope">
                <el-button link type="primary" @click="viewBatchDetail(scope.row)">详情</el-button>
                <el-button link type="primary" @click="trackBatch(scope.row)">追踪</el-button>
                <el-button link type="danger" @click="handleExpired(scope.row)" v-if="scope.row.status === 'expiring_soon'">处理</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="pagination.currentPage"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pagination.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 新建批次对话框 -->
    <el-dialog
      v-model="batchDialogVisible"
      title="新建批次"
      width="50%"
    >
      <el-form :model="batchForm" label-width="120px" ref="batchFormRef">
        <el-form-item label="物料编码" prop="materialCode">
          <el-input v-model="batchForm.materialCode" placeholder="请输入物料编码" />
        </el-form-item>
        <el-form-item label="物料名称" prop="materialName">
          <el-input v-model="batchForm.materialName" placeholder="请输入物料名称" />
        </el-form-item>
        <el-form-item label="批次号" prop="batchNumber">
          <el-input v-model="batchForm.batchNumber" placeholder="请输入批次号" />
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input-number v-model="batchForm.quantity" :min="1" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-select v-model="batchForm.unit" placeholder="请选择单位">
            <el-option label="个" value="个" />
            <el-option label="箱" value="箱" />
            <el-option label="件" value="件" />
            <el-option label="kg" value="kg" />
            <el-option label="吨" value="吨" />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库" prop="warehouseId">
          <el-select v-model="batchForm.warehouseId" placeholder="请选择仓库">
            <el-option 
              v-for="warehouse in warehouses" 
              :key="warehouse.id" 
              :label="warehouse.name" 
              :value="warehouse.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="货位" prop="locationCode">
          <el-input v-model="batchForm.locationCode" placeholder="请输入货位编码" />
        </el-form-item>
        <el-form-item label="生产日期" prop="manufacturingDate">
          <el-date-picker 
            v-model="batchForm.manufacturingDate" 
            type="date" 
            placeholder="请选择生产日期" 
          />
        </el-form-item>
        <el-form-item label="过期日期" prop="expiryDate">
          <el-date-picker 
            v-model="batchForm.expiryDate" 
            type="date" 
            placeholder="请选择过期日期" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveBatch">保存</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 批次详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="批次详情"
      width="60%"
    >
      <div v-if="selectedBatch" class="batch-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="批次号">{{ selectedBatch.batchNumber }}</el-descriptions-item>
          <el-descriptions-item label="物料编码">{{ selectedBatch.materialCode }}</el-descriptions-item>
          <el-descriptions-item label="物料名称">{{ selectedBatch.materialName }}</el-descriptions-item>
          <el-descriptions-item label="数量">{{ selectedBatch.quantity }} {{ selectedBatch.unit }}</el-descriptions-item>
          <el-descriptions-item label="生产日期">{{ selectedBatch.manufacturingDate }}</el-descriptions-item>
          <el-descriptions-item label="过期日期">{{ selectedBatch.expiryDate }}</el-descriptions-item>
          <el-descriptions-item label="剩余有效期">{{ selectedBatch.remainingDays }} 天</el-descriptions-item>
          <el-descriptions-item label="仓库">{{ selectedBatch.warehouseName }}</el-descriptions-item>
          <el-descriptions-item label="货位">{{ selectedBatch.locationCode }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(selectedBatch.status)">
              {{ getStatusLabel(selectedBatch.status) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'BatchTracking',
  setup() {
    // 状态变量
    const loading = ref(false)
    const batchDialogVisible = ref(false)
    const detailDialogVisible = ref(false)
    const selectedBatch = ref(null)
    const batchFormRef = ref(null)
    
    // 仓库数据
    const warehouses = ref([
      { id: 'WH001', name: '中央仓库' },
      { id: 'WH002', name: '北区配送中心' },
      { id: 'WH003', name: '南方仓储中心' },
      { id: 'WH004', name: '西部物流中心' }
    ])
    
    // 过滤表单
    const filterForm = reactive({
      materialCode: '',
      batchNumber: '',
      warehouseId: '',
      status: ''
    })
    
    // 批次表单
    const batchForm = reactive({
      materialCode: '',
      materialName: '',
      batchNumber: '',
      quantity: 1,
      unit: '个',
      warehouseId: '',
      locationCode: '',
      manufacturingDate: '',
      expiryDate: ''
    })
    
    // 分页数据
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    // 批次列表数据
    const batchList = ref([])
    
    // 加载批次数据
    const loadBatchData = () => {
      loading.value = true
      
      // 模拟API调用
      setTimeout(() => {
        // 生成模拟批次数据
        batchList.value = [
          {
            id: 'B001',
            batchNumber: 'BT20240601001',
            materialCode: 'M10012',
            materialName: '不锈钢螺丝 M6',
            quantity: 1000,
            unit: '个',
            manufacturingDate: '2024-06-01',
            expiryDate: '2026-06-01',
            remainingDays: 730,
            warehouseId: 'WH001',
            warehouseName: '中央仓库',
            locationCode: 'A-01-02-03',
            status: 'in_stock'
          },
          {
            id: 'B002',
            batchNumber: 'BT20240520002',
            materialCode: 'M20045',
            materialName: '铝合金外壳',
            quantity: 200,
            unit: '件',
            manufacturingDate: '2024-05-20',
            expiryDate: '2024-08-20',
            remainingDays: 15,
            warehouseId: 'WH001',
            warehouseName: '中央仓库',
            locationCode: 'A-02-03-01',
            status: 'expiring_soon'
          },
          {
            id: 'B003',
            batchNumber: 'BT20240415003',
            materialCode: 'P30078',
            materialName: '包装盒 30x20cm',
            quantity: 500,
            unit: '个',
            manufacturingDate: '2024-04-15',
            expiryDate: '2025-04-15',
            remainingDays: 254,
            warehouseId: 'WH002',
            warehouseName: '北区配送中心',
            locationCode: 'B-03-01-04',
            status: 'in_stock'
          },
          {
            id: 'B004',
            batchNumber: 'BT20240320004',
            materialCode: 'C40056',
            materialName: '控制电路板',
            quantity: 0,
            unit: '个',
            manufacturingDate: '2024-03-20',
            expiryDate: '2026-03-20',
            remainingDays: 638,
            warehouseId: 'WH001',
            warehouseName: '中央仓库',
            locationCode: 'A-04-02-05',
            status: 'out_of_stock'
          },
          {
            id: 'B005',
            batchNumber: 'BT20240210005',
            materialCode: 'M50023',
            materialName: '液压油',
            quantity: 50,
            unit: 'kg',
            manufacturingDate: '2024-02-10',
            expiryDate: '2024-07-10',
            remainingDays: -26,
            warehouseId: 'WH003',
            warehouseName: '南方仓储中心',
            locationCode: 'C-01-03-02',
            status: 'expired'
          }
        ]
        
        // 更新总数
        pagination.total = 5
        
        loading.value = false
      }, 500)
    }
    
    // 搜索批次
    const searchBatches = () => {
      pagination.currentPage = 1
      loadBatchData()
    }
    
    // 重置筛选条件
    const resetFilter = () => {
      Object.assign(filterForm, {
        materialCode: '',
        batchNumber: '',
        warehouseId: '',
        status: ''
      })
      searchBatches()
    }
    
    // 新建批次
    const createBatch = () => {
      Object.assign(batchForm, {
        materialCode: '',
        materialName: '',
        batchNumber: '',
        quantity: 1,
        unit: '个',
        warehouseId: '',
        locationCode: '',
        manufacturingDate: '',
        expiryDate: ''
      })
      batchDialogVisible.value = true
    }
    
    // 保存批次
    const saveBatch = () => {
      // 模拟API调用
      setTimeout(() => {
        ElMessage.success('批次创建成功')
        batchDialogVisible.value = false
        loadBatchData()
      }, 500)
    }
    
    // 查看批次详情
    const viewBatchDetail = (batch) => {
      selectedBatch.value = batch
      detailDialogVisible.value = true
    }
    
    // 追踪批次
    const trackBatch = (batch) => {
      ElMessage.info(`正在追踪批次: ${batch.batchNumber}`)
    }
    
    // 处理即将过期
    const handleExpired = (batch) => {
      ElMessageBox.confirm(
        `批次 ${batch.batchNumber} 即将在 ${batch.remainingDays} 天后过期，是否标记为需处理？`,
        '过期预警',
        {
          confirmButtonText: '标记',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        ElMessage.success(`已标记批次 ${batch.batchNumber} 为需处理`)
      })
    }
    
    // 获取状态标签类型
    const getStatusTagType = (status) => {
      switch (status) {
        case 'in_stock':
          return 'success'
        case 'out_of_stock':
          return 'info'
        case 'expired':
          return 'danger'
        case 'expiring_soon':
          return 'warning'
        default:
          return 'info'
      }
    }
    
    // 获取状态标签文本
    const getStatusLabel = (status) => {
      switch (status) {
        case 'in_stock':
          return '在库'
        case 'out_of_stock':
          return '已出库'
        case 'expired':
          return '已过期'
        case 'expiring_soon':
          return '即将过期'
        default:
          return '未知'
      }
    }
    
    // 获取有效期标签类型
    const getExpiryTagType = (days) => {
      if (days < 0) return 'danger'
      if (days <= 30) return 'warning'
      if (days <= 90) return 'info'
      return 'success'
    }
    
    // 处理页码变更
    const handleCurrentChange = (val) => {
      pagination.currentPage = val
      loadBatchData()
    }
    
    // 处理每页条数变更
    const handleSizeChange = (val) => {
      pagination.pageSize = val
      loadBatchData()
    }
    
    // 页面加载时获取数据
    onMounted(() => {
      loadBatchData()
    })
    
    return {
      loading,
      warehouses,
      filterForm,
      batchList,
      pagination,
      batchDialogVisible,
      detailDialogVisible,
      batchForm,
      batchFormRef,
      selectedBatch,
      
      searchBatches,
      resetFilter,
      createBatch,
      saveBatch,
      viewBatchDetail,
      trackBatch,
      handleExpired,
      getStatusTagType,
      getStatusLabel,
      getExpiryTagType,
      handleCurrentChange,
      handleSizeChange
    }
  }
}
</script>

<style>
.batch-tracking-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-container {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.batch-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.batch-detail {
  padding: 10px;
}

/* 确保下拉框宽度为180px */
.el-select {
  width: 180px !important;
}

/* 特殊情况下需要100%宽度的select */
.full-width-select .el-select {
  width: 100% !important;
}
</style> 